<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/6/22 0022
 * Time: 15:35
 */

namespace app\api\controller\v1\member;


use app\api\controller\v1\Member;
use app\wechat\service\WechatService;
use library\tools\Data;
use think\Db;
use think\exception\HttpResponseException;

class IntegralRecharge extends Member
{
    /**
     * 发起积分充值
     */
    public function save()
    {
        $data = $this->_input([
            'number' => $this->request->post('number')
        ],[
            'number' => 'require|number'
        ],[
            'number.require' => '请输入积分数量！',
            'number.number' => '积分数量只能为数字！'
        ]);
        $integral_recharge_discount = sysconf('integral_recharge_discount') ?: 1;
        $integral_recharge_rule = trim(sysconf('integral_recharge_rule'));
        $integral_recharge_rule = array_filter(explode("|",$integral_recharge_rule));
        if(!in_array($data['number'], $integral_recharge_rule))
        {
            $this->error('请输入正确的积分数量！');
        }
        $order = [
            'mid' => $this->mid,
            'order_no' => Data::uniqidNumberCode(12),
            'integral' => $data['number'],
            'total_price' => $data['number'] * $integral_recharge_discount
        ];
        try {
            // 订单数据写入
            Db::name('MemberIntegralOrder')->insert($order);
            $param = $this->getPayParams($order['order_no'], $order['total_price']);
            $this->success('订单创建成功！', $param);
        } catch (HttpResponseException $exception) {
            throw $exception;
        } catch (\Exception $e) {
            $this->error("创建订单失败，请稍候再试！{$e->getMessage()}");
        }
    }

    /**
     * 获取订单支付参数
     * @param string $order_no
     * @param string $total_price
     * @return array
     * @throws \WeChat\Exceptions\InvalidResponseException
     * @throws \WeChat\Exceptions\LocalCacheException
     * @throws \think\Exception
     */
    protected function getPayParams($order_no,$total_price)
    {
        $options = [
            'body'             => '用户-积分充值支付',
            'openid'           => $this->member->openid,
            'out_trade_no'     => $order_no,
            'total_fee'        => $total_price * 100,
            'trade_type'       => 'JSAPI',
            'notify_url'       => url('api/v1/wx_notify', ['id' => 'integral'], false, true),
            'spbill_create_ip' => $this->request->ip(),
        ];
        $pay = WechatService::WePayOrder();
        $info = $pay->create($options);
        if ($info['return_code'] === 'SUCCESS' && $info['result_code'] === 'SUCCESS') {
            return $pay->jsapiParams($info['prepay_id']);
        }
        if (isset($info['err_code_des'])) {
            throw new \think\Exception($info['err_code_des']);
        } else {
            throw new \think\Exception('未知错误！');
        }
    }
}